import { Result } from "@/types/service";
import storage from "@/utils/storage";
import axios, { AxiosError, AxiosRequestConfig } from "axios";
import { message } from "antd";

// 全局loading/报错
interface IConfig extends AxiosRequestConfig {
  showError?: boolean; // 是否显示错误提示
}

// 创建实例
const instance = axios.create({
  baseURL: "http://localhost:3002",
  // timeout: 180000,
  timeoutErrorMessage: "请求超时,请稍后再试",
  withCredentials: false,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = storage.get("token");
    // 如果已登录，给每个请求添加token
    if (token) {
      config.headers.token = token;
    }

    return {
      ...config,
    };
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    console.log("response.config:", response);
    const data: Result = response.data;
    // 如果是文件流，直接返回
    if (response.config.responseType === "blob") return response;
    if (data.code === 401) {
      message.error(data.message);
      storage.remove("token");
    } else if (data.code && data.code != 200) {
      message.error(data.message);
      return Promise.reject(data);
    }
    return data.data;
  },
  (error) => {
    const { code, response } = error;
    // 处理其他的一些自定义错误
    if (response?.status === 601) {
      location.href = "/601";
      return;
    }

    if (code === "ERR_NETWORK") {
      location.href = "/500";
      return;
    }

    return Promise.reject(error.message);
  }
);

export default {
  get<T>(
    url: string,
    params?: object,
    options: IConfig = { showError: true }
  ): Promise<T> {
    return instance.get(url, { params, ...options });
  },
  post<T>(
    url: string,
    params?: object,
    options: IConfig = { showError: true }
  ): Promise<T> {
    return instance.post(url, params, options);
  },
  put<T>(
    url: string,
    params?: object,
    options: IConfig = { showError: true }
  ): Promise<T> {
    return instance.put(url, params, options);
  },
  delete<T>(
    url: string,
    params?: object,
    options: IConfig = { showError: true }
  ): Promise<T> {
    return instance.delete(url, { params, ...options });
  },
};
